/**
 * @author philippdatz
 */

	
	window.addEvent('domready', function() {
	
		/* variables */
		site = "<?php if ( isset($_GET['page']) && $_GET['page'] !== '' ) echo $_GET['page']; ?>";
		tool = '';
		
		if ( Cookie.read('pages') == 1 ) {
			buildPageBox();
			$('pages').addClass('selected');
		}
		
		info = new Element('div', {
			'id': 'info',
			'styles': {
				'top': 5,
				'right': 100,
				'display': 'none'
			}
		}).inject($('body'));
		
		$('sidebar').addEvents({
			'mouseenter': function(){
				this.set('tween', {
					duration: 200,
					transition: Fx.Transitions.Quad.easeOut
				}).tween('top', '0px');
			},
			'mouseleave': function(){
				this.set('tween', {
					duration: 200,
					transition: Fx.Transitions.Quad.easeOut	
				}).tween('top', '-22px');
			}
		});
		
		$('drawer').addEvents({
			
			'mousemove': function(e) {
				//$('info').set('html', el.getStyle('width') + ',' + el.getStyle('height'));
			},
			'mousedown': function(e) {
				
				if ( tool == 'add_box') {
				
					//info.set('styles', { display: 'block' });
					
					var length = $$('div.entry').length
					el = new Element('div', {
						'class': 'entry',
						'id': 'entry' + length,
						'styles': {
							'top': e.page.y.round(-1),
							'left': e.page.x.round(-1)
						}
					}).inject($('contents'));
					
					myResize = el.makeResizable({
						grid: 10,
						onComplete: function() {
							
							this.detach();
							
						}}).start(e);
					/*
					info.set('styles', {
						top: e.page.y.round(-1) - 15,
						left: e.page.x.round(-1)
					});*/
						
				}
			},
			'mouseup': function(e) {
				if (tool == 'add_box') {
				
					buildEntry(el, "Nothing in here ...");
					el = '';
					//info.set('styles', { display: 'none' });
				}
			}
		});
		
		/* load template */
		
		var loadTemplateReq = new Request.JSON({
			url: '<?php echo $baseurl; ?>loadpage',
			onComplete: function(jsonObj) {
				
				$('loader').setStyle('display', 'none');
				
				if (jsonObj) {
					
					entries = $$('div.entries').length;
					jsonObj.entries.each(function(entry) {
						
						var el = new Element('div', {
							'class': 'templateentry',
							'id': 'entry' + entries,
							'styles': {
								'top': entry.top,
								'left': entry.left,
								'height': entry.height,
								'width': entry.width,
								'z-index': -9999
							}
						}).inject($('contents'));
						entries++;
					});
				}
				/* load current site */
				loadSite();
			}
		}).send('site=template');
		
		
		
		
		/* sidebar - menu */
		
		
		$('add_box').addEvent('click', function() {
			tool = this.id;
			$$('div#sidebar a').removeClass('selected');
			this.addClass('selected');
		
		});
		
		$('add_text').addEvent('click', function() {
			tool = this.id;
			$$('div#sidebar a').removeClass('selected');
			this.addClass('selected');
		
		});
		
		$('save').addEvent('click', function() {
			saveSite();
		});
		
		$('pages').addEvent('click', function() {
			
			tool = '';
			this.toggleClass('selected');
			
			if ( this.hasClass('selected')) {
				var pageCookie = Cookie.write('pages', 1);
				buildPageBox();

			} else {
				$('pages_container').destroy();
				var pageCookie = Cookie.write('pages', 0);
				
			}
		});
	});
	
	
	
	
	/* functions */
	
	
	var loadSite = function() {
		
		var loadReq = new Request.JSON({
			url: '<?php echo $baseurl; ?>loadpage',
			onComplete: function(jsonObj) {
				
				$('loader').setStyle('display', 'none');
				
				if (jsonObj) {
					
					entries = $$('div.entries').length;
					jsonObj.entries.each(function(entry) {
					
						var el = new Element('div', {
							'class': 'entry',
							'id': 'entry' + entries,
							'styles': {
								'top': entry.top,
								'left': entry.left,
								'height': entry.height,
								'width': entry.width
							}
						}).inject($('contents'));
						buildEntry( el, entry.content );
						entries++;
					});
				} else {
					$('info').set({
						'styles': {
						'display': 'block'
					},
						'html': 'Diese Seite existiert noch nicht.'
					});
				}
			}
		}).send('site=' + site);
		
	};
	
	var saveSite = function() {
		
		$('loader').setStyle('display', 'block');
		
		var entries = $$('div.entry');
		var data = '';
		var i = 0;
		var count = entries.length;
		
		if (entries.length > 0) {
		
			data += '{"entries":[';
			
			entries.each(function(item, index){
			
				data += '{'
				
					//data += '"id": ' + i + ', ';
					data += '"top": ' + item.getCoordinates()['top'] + ', ';
					data += '"left": ' + item.getCoordinates()['left'] + ', ';
					data += '"height": ' + item.getCoordinates()['height'].round(-1) + ', ';
					data += '"width": ' + item.getCoordinates()['width'].round(-1) + ', ';
					data += '"content": ' + '"' + item.getElement('div').get('html').replace(/"/g, '\\"') + '"';
				
				data += '}';
				++i;
				if (i < count) 
					data += ', ';
			});
			
			data += ']}';
			
		} 
		
		var saveReq = new Request({
			url: '<?php echo $baseurl; ?>save',
			onComplete: function(){
				$('loader').setStyle('display', 'none');
			}
		}).send("site=" + site + "&data=" + data );
		
	};
	
	var buildEntry = function( entry, content ) {
		
		var form = new Element('form').inject(entry);
		
		var holder = new Element('div', {
			'id': entry.id + '_holder_div',
			'class': 'holder',
			'html': content
		}).inject(entry, 'top');
		
		var contentHolder = new Element('textarea', {
			'class': 'holder',
			'id': 	entry.id + '_holder',
			'html': content
		}).inject(form);
		
		resizeContentHolder(entry, contentHolder);
		
		var editor = new Element('a', {
			'class': 'edit',
			'html': 'edit',
			'events': {
				'click': function() {
					toggleEditor(this.getPrevious('form').getElement('textarea').id);
				}
			}
		}).inject(entry);
		
		var deleter = new Element('a', {
			'class': 'delete',
			'html': 'x',
			'events': {
				'click': function() {
					this.getParent().destroy();
				}
			}
		}).inject(entry);
		
		var dragger = new Element('div', {
			'class': 'dragger'
		}).inject(entry);
		
		var resizer = new Element('div', {
			'class': 'resizer'
		}).inject(entry);
		
		entry.makeDraggable({
			handle: entry.getElements('.dragger'),
			grid: 10,
			onComplete: function(){
				saveSite();
			}
		});
		
		entry.makeResizable({
			handle: entry.getElements('.resizer'),
			grid: 10,
			onComplete: function(){
				resizeContentHolder(entry, contentHolder);
				saveSite();
			}
		});
	};	
	
	var buildPageBox = function() {
		
		var el = new Element('div', {
			'id': 'pages_container',
			'styles': {
				'top': '100px',
				'left': '100px'
			}
		}).inject($('body'));
		
		el.makeDraggable();
		
		var loadPagesReq = new Request.JSON({
			url: '<?php echo $baseurl; ?>loadpages',
			onComplete: function(jsonObj){
				
				if (jsonObj) {
				
					jsonObj.pages.each(function(page){
					
						var p = new Element('p').inject(el);
						
						var a = new Element('a', {
							'html': page,
							'href': '<?php echo $baseurl; ?>' + page
						}).inject(p);
						
						var del = new Element('a', {
							'html': 'x',
							'events': {
								'click': function(){
									var check = confirm("Wollen Sie diese Seite wirklich loeschen?");
									if (check == true) {
										var deletePagesReq = new Request({
											url: '<?php echo $baseurl; ?>deletepage',
											onComplete: function(){
												li.destroy();
											}
										}).send('site=' + page);
									}
								}
							}
						}).inject(p);
					});
					
				}
			}
		}).send();
		
	};
	
	var resizeContentHolder = function(entry, contentHolder) {
		contentHolder.setStyles({
			'width': entry.getStyle('width').toInt() - 10,
			'height': entry.getStyle('height').toInt() - 30
		});
	};
